package com.ztsoft.user.service.project.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztsoft.user.common.exception.CustomException;
import com.ztsoft.user.mapper.project.ProjectMapper;
import com.ztsoft.user.mapper.project.UserProjectMapper;
import com.ztsoft.user.mapper.user.SysUserMapper;
import com.ztsoft.user.pojo.constant.UserConstant;
import com.ztsoft.user.pojo.entity.project.*;
import com.ztsoft.user.pojo.entity.user.SysRole;
import com.ztsoft.user.pojo.entity.user.SysUser;
import com.ztsoft.user.pojo.entity.user.SysUserDemand;
import com.ztsoft.user.pojo.entity.user.SysUserRole;
import com.ztsoft.user.pojo.enums.ResultCode;
import com.ztsoft.user.pojo.vo.PageData;
import com.ztsoft.user.pojo.vo.PageInfo;
import com.ztsoft.user.pojo.vo.user.UserDemandUnit;
import com.ztsoft.user.service.project.*;
import com.ztsoft.user.service.user.SysRoleService;
import com.ztsoft.user.service.user.SysUserDemandService;
import com.ztsoft.user.service.user.SysUserRoleService;
import com.ztsoft.user.service.user.SysUserService;
import com.ztsoft.user.utils.FieldsUtils;
import com.ztsoft.user.utils.Result;
import com.ztsoft.user.utils.UserHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;

@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private UserProjectService userProjectService;
    @Resource
    private UserManageService userManageService;
    @Resource
    private UserQuoteService userQuoteService;
    @Resource
    private DemandUnitService demandUnitService;
    @Resource
    private SysUserDemandService userDemandService;
    @Resource
    private AnswerQuoteService answerQuoteService;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private UserProjectMapper userProjectMapper;

    @Override
    public Result<Object> updateProject(Project project) {
        if (updateById(project)) {
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> addProject(Project project) {
        // 1、获取登录账号信息
        UserHolder userInfo = sysUserService.getUserInfo();
        SysUser sysUser = userInfo.getSysUser();
        List<SysRole> roleList = userInfo.getRoleList();

        project.setRegion(project.getRegion().replace("/", ""));

        // 2、如果是管理员级别创建（管理员添加，直接入库，不需要审核）
        if (Boolean.TRUE.equals(isAdmin(roleList))) {
            // 2.1保存审核通过项目
            project.setStatus(2);

            save(project);  // 先保存，生成id

            // 2.2添加管理员与项目关联关系
            userProjectService.save(new UserProject(sysUser.getUserId(), project.getId()));
        }else{
            // 3、如果是子代理机构创建
            // 3.1保存待审核项目
            project.setStatus(1);
            save(project);  // 先保存，生成id
            // 3.2添加子代理与项目关联关系
            userProjectService.save(new UserProject(sysUser.getUserId(), project.getId()));

            // 3.3添加管理员与项目关联关系
            List<SysUser> sysUserList = getAdmin();
            for (SysUser user : sysUserList) {
                userProjectService.save(new UserProject(user.getUserId(), project.getId()));
            }
        }
        return Result.success();
    }

    @Override
    public Result<Object> deleteProject(String id) {
        if (removeById(id)) {
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> getProject(Integer currentPage, Integer pageSize, String infoNumber, String projectName) {
        // 登录用户的信息
        SysUser sysUser = sysUserService.getUserInfo2().getSysUser();

        // 查询用户与项目之间的关系
        List<String> projectIds =userProjectMapper.selectProjectList(sysUser.getUserId());
        if (projectIds.isEmpty()) {
            return Result.success(new PageData(Collections.emptyList(), new PageInfo(pageSize, currentPage, 0)));
        }
        // 查询项目
        QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
        projectQueryWrapper.in("id", projectIds);
        if (ObjectUtil.isNotNull(infoNumber)) {
            // 查找条件-项目编号
            projectQueryWrapper.like("info_number", infoNumber);
        }
        if (ObjectUtil.isNotNull(projectName)) {
            // 查找条件-项目名称
            projectQueryWrapper.like("name", projectName);
        }
        Page<Project> page = new Page<>(currentPage, pageSize);
        Page<Project> projectPage = page(page, projectQueryWrapper);
        List<Project> projectList = projectPage.getRecords();

        // 把实体字段换成动态表格标准
        List<Map<String, Object>> result = getProjectResultMap(projectList);

        return Result.success(new PageData(result, new PageInfo(pageSize, currentPage, (int) projectPage.getTotal())));
    }

    @Override
    public Result<Object> getUserAndProject(String projectId, Integer currentPage, Integer pageSize,
                                            String userAccount, String userName, String roleName, String region) {

        // 查找登录用户管理用户id
        List<String> manageUserIds = getManageUserIds();

        if (CollectionUtils.isEmpty(manageUserIds)) {
            return Result.success(new PageData(Collections.emptyList(), new PageInfo(pageSize, currentPage, 0)));
        }

        // 查找已存在关联的用户id
        List<String> userIds = userProjectMapper.selectUserList(projectId);
        // 查找排除掉已存在关联的用户的其他用户
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.in("user_id", manageUserIds);
        if(!CollectionUtils.isEmpty(userIds)){
            sysUserQueryWrapper.notIn("user_id", userIds);
        }
        if (ObjectUtil.isNotNull(userAccount)) {
            // 查找条件-用户账号
            sysUserQueryWrapper.like("user_account", userAccount);
        }
        if (ObjectUtil.isNotNull(userName)) {
            // 查找条件-用户名
            sysUserQueryWrapper.like("user_name", userName);
        }
        if (ObjectUtil.isNotNull(region)) {
            // 查找条件-地市
            sysUserQueryWrapper.like("region", region);
        }
        if (ObjectUtil.isNotNull(roleName)) {
            // 查找条件-角色名
            QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
            sysRoleQueryWrapper.like("role_name", roleName);
            List<SysRole> sysRoleList = sysRoleService.list(sysRoleQueryWrapper);
            List<String> roleIds = new ArrayList<>();
            sysRoleList.forEach(sysRole -> roleIds.add(sysRole.getRoleId()));

            QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
            sysUserRoleQueryWrapper.in("role_id", roleIds);
            List<SysUserRole> sysUserRoles = sysUserRoleService.list(sysUserRoleQueryWrapper);
            List<String> ids = new ArrayList<>();
            sysUserRoles.forEach(sysUserRole -> ids.add(sysUserRole.getUserId()));

            sysUserQueryWrapper.in("user_id", ids);
        }

        Page<SysUser> userPage = new Page<>(currentPage, pageSize);
        Page<SysUser> sysUserPage = sysUserService.page(userPage, sysUserQueryWrapper);

        // 封装返回
        return Result.success(new PageData(composeUserInfo(sysUserPage.getRecords()), new PageInfo(pageSize, currentPage, (int) sysUserPage.getTotal())));
    }

    @Override
    public Result<Object> getExistUserAndProject(String projectId, Integer currentPage, Integer pageSize) {
        // 查找登录用户管理用户id
        List<String> manageUserIds = getManageUserIds();

        if (CollectionUtils.isEmpty(manageUserIds)) {
            return Result.success(new PageData(Collections.emptyList(), new PageInfo(pageSize, currentPage, 0)));
        }

        // 查询用户与项目之间的关系
        QueryWrapper<UserProject> userProjectQueryWrapper = new QueryWrapper<>();
        userProjectQueryWrapper.in("user_id", manageUserIds).eq("project_id", projectId);
        Page<UserProject> page = new Page<>(currentPage, pageSize);
        Page<UserProject> userProjectPage = userProjectService.page(page, userProjectQueryWrapper);
        List<UserProject> userProjectList = userProjectPage.getRecords();

        // 查询已存在关系用户
        List<SysUser> existUserList = new ArrayList<>();
        userProjectList.forEach(userProject -> existUserList.add(sysUserService.getById(userProject.getUserId())));

        // 封装返回
        return Result.success(new PageData(composeUserInfo(existUserList), new PageInfo(pageSize, currentPage, (int) userProjectPage.getTotal())));
    }


    @Override
    public Result<Object> updateUserAndProject(String projectId, Integer type, List<String> userIds) {
        if (type == 1) {
            // 新增
            userIds.forEach(userId ->
                    userProjectService.save(new UserProject(userId, projectId))
            );
            return Result.success();
        } else if (type == 2) {
            List<SysUser> adminUsers = getAdmin();
            for (String userId : userIds) {
                SysUser sysUser = sysUserService.getById(userId);
                if (adminUsers.contains(sysUser)) {
                    return Result.returnMsg("所移除用户包含了管理员，移除失败！", ResultCode.FAILED.getCode());
                }
            }

            // 删除
            QueryWrapper<UserProject> userProjectQueryWrapper = new QueryWrapper<>();
            userProjectQueryWrapper.eq("project_id", projectId).in("user_id", userIds);

            userProjectService.remove(userProjectQueryWrapper);
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> getChildAgencies(Integer currentPage, Integer pageSize,
                                           String userAccount, String userName, String region) {
        List<SysUser> agencyUserList = getAgency();
        List<String> agencyUserIds = new ArrayList<>();
        agencyUserList.forEach(agencyUser -> agencyUserIds.add(agencyUser.getUserId()));

        if (CollectionUtils.isEmpty(agencyUserIds)) {
            return Result.success(new PageData(Collections.emptyList(), new PageInfo(pageSize, currentPage, 0)));
        }

        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.in("user_id", agencyUserIds);

        if (ObjectUtil.isNotNull(userAccount)) {
            // 查找条件-用户账号
            sysUserQueryWrapper.like("user_account", userAccount);
        }
        if (ObjectUtil.isNotNull(userName)) {
            // 查找条件-用户名
            sysUserQueryWrapper.like("user_name", userName);
        }
        if (ObjectUtil.isNotNull(region)) {
            // 查找条件-地市
            sysUserQueryWrapper.like("region", region);
        }

        Page<SysUser> userPage = new Page<>(currentPage, pageSize);
        Page<SysUser> sysUserPage = sysUserService.page(userPage, sysUserQueryWrapper);

        // 封装返回
        return Result.success(new PageData(composeUserInfo(sysUserPage.getRecords()), new PageInfo(pageSize, currentPage, (int) sysUserPage.getTotal())));
    }

    @Override
    public Result<Object> getUserAndManage(String manageId, Integer currentPage, Integer pageSize, String userAccount, String userName, String roleName, String region) {

        // 查找已存在关联的用户id
        QueryWrapper<UserManage> userManageQueryWrapper = new QueryWrapper<>();
        userManageQueryWrapper.eq("manage_id", manageId);
        List<UserManage> userManageList = userManageService.list(userManageQueryWrapper);
        List<String> userIds = new ArrayList<>();
        userManageList.forEach(userManage -> userIds.add(userManage.getUserId()));

        // 查找排除掉已存在关联的用户的其他用户
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        if (!CollectionUtils.isEmpty(userIds)) {
            sysUserQueryWrapper.notIn("user_id", userIds);
        }

        if (ObjectUtil.isNotNull(userAccount)) {
            // 查找条件-用户账号
            sysUserQueryWrapper.like("user_account", userAccount);
        }
        if (ObjectUtil.isNotNull(userName)) {
            // 查找条件-用户名
            sysUserQueryWrapper.like("user_name", userName);
        }
        if (ObjectUtil.isNotNull(region)) {
            // 查找条件-地市
            sysUserQueryWrapper.like("region", region);
        }
        if (ObjectUtil.isNotNull(roleName)) {
            // 查找条件-角色名
            QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
            sysRoleQueryWrapper.eq("role_name", roleName);
            SysRole sysRole = sysRoleService.getOne(sysRoleQueryWrapper);
            QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
            sysUserRoleQueryWrapper.eq("role_id", sysRole.getRoleId());
            List<SysUserRole> sysUserRoles = sysUserRoleService.list(sysUserRoleQueryWrapper);
            List<String> ids = new ArrayList<>();
            sysUserRoles.forEach(sysUserRole -> ids.add(sysUserRole.getUserId()));

            sysUserQueryWrapper.in("user_id", ids);
        }

        Page<SysUser> userPage = new Page<>(currentPage, pageSize);
        Page<SysUser> sysUserPage = sysUserService.page(userPage, sysUserQueryWrapper);

        // 封装返回
        return Result.success(new PageData(composeUserInfo(sysUserPage.getRecords()), new PageInfo(pageSize, currentPage, (int) sysUserPage.getTotal())));
    }

    @Override
    public Result<Object> getExistUserAndManage(String manageId, Integer currentPage, Integer pageSize, String userName, String region) {
        // 查找已存在关联的用户id
        QueryWrapper<UserManage> userManageQueryWrapper = new QueryWrapper<>();
        userManageQueryWrapper.eq("manage_id", manageId);
        List<UserManage> userManageList = userManageService.list(userManageQueryWrapper);
        List<String> userIds = new ArrayList<>();
        userManageList.forEach(userManage -> userIds.add(userManage.getUserId()));

        if (CollectionUtils.isEmpty(userIds)) {
            return Result.success(new PageData(Collections.emptyList(), new PageInfo(pageSize, currentPage, 0)));
        }

        // 查找排除掉已存在关联的用户的其他用户
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(userName)) {
            sysUserQueryWrapper.like("user_name", userName);
        }
        if (ObjectUtil.isNotNull(region)) {
            sysUserQueryWrapper.like("region", region);
        }

        sysUserQueryWrapper.in("user_id", userIds);

        Page<SysUser> userPage = new Page<>(currentPage, pageSize);
        Page<SysUser> sysUserPage = sysUserService.page(userPage, sysUserQueryWrapper);

        // 封装返回
        return Result.success(new PageData(composeUserInfo(sysUserPage.getRecords()), new PageInfo(pageSize, currentPage, (int) sysUserPage.getTotal())));
    }

    @Override
    public Result<Object> updateUserAndManage(String manageId, Integer type, List<String> userIds) {
        if (type == 1) {
            // 新增
            userIds.forEach(userId ->
                    userManageService.save(new UserManage(manageId, userId))
            );
            return Result.success();
        } else if (type == 2) {
            // 删除
            QueryWrapper<UserManage> userProjectQueryWrapper = new QueryWrapper<>();
            userProjectQueryWrapper.eq("manage_id", manageId).in("user_id", userIds);

            userManageService.remove(userProjectQueryWrapper);
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> queryUserAndDemandUnit(Integer currentPage, Integer pageSize,
                                                 String userName, String demandUnitName,
                                                 String region, Date userCreateTime, Date demandUnitCreateTime) {
        SysUser loginUser = sysUserService.getUserInfo().getSysUser();

        // 条件查询需求单位
        QueryWrapper<DemandUnit> demandUnitQueryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(demandUnitName)) {
            demandUnitQueryWrapper.like("demand_unit_name", demandUnitName);
        }
        if (ObjectUtil.isNotNull(demandUnitCreateTime)) {
            demandUnitQueryWrapper.eq("create_time", demandUnitCreateTime);
        }
        List<DemandUnit> demandUnitList = demandUnitService.list(demandUnitQueryWrapper);

        // 查找需求单位对应关联的用户id列表
        List<String> demandUnitUserIds = new ArrayList<>();
        for (DemandUnit demandUnit : demandUnitList) {
            QueryWrapper<SysUserDemand> userDemandUnitQueryWrapper = new QueryWrapper<>();
            userDemandUnitQueryWrapper.eq("demand_unit_id", demandUnit.getId());
            List<SysUserDemand> sysUserDemandList = userDemandService.list(userDemandUnitQueryWrapper);
            sysUserDemandList.forEach(sysUserDemand -> demandUnitUserIds.add(sysUserDemand.getUserId()));
        }

        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(userName)) {
            sysUserQueryWrapper.like("user_name", userName);
        }
        if (ObjectUtil.isNotNull(region)) {
            sysUserQueryWrapper.like("region", region);
        }
        if (ObjectUtil.isNotNull(userCreateTime)) {
            sysUserQueryWrapper.eq("create_time", userCreateTime);
        }
        if (ObjectUtil.isNotNull(demandUnitName)) {
            sysUserQueryWrapper.in("user_id", demandUnitUserIds);
        }

        // 查找已存在关联的用户id
        QueryWrapper<UserManage> userManageQueryWrapper = new QueryWrapper<>();
        userManageQueryWrapper.eq("manage_id", loginUser.getUserId());
        List<UserManage> userManageList = userManageService.list(userManageQueryWrapper);
        List<String> userIds = new ArrayList<>();
        userManageList.forEach(userManage -> userIds.add(userManage.getUserId()));

        if (CollectionUtils.isEmpty(userIds)) {
            return Result.success(new PageData(Collections.emptyList(), new PageInfo(pageSize, currentPage, 0)));
        }

        sysUserQueryWrapper.in("user_id", userIds);

        Page<SysUser> page = new Page<>(currentPage, pageSize);
        Page<SysUser> sysUserPage = sysUserService.page(page, sysUserQueryWrapper);
        List<SysUser> sysUserList = sysUserPage.getRecords();

        // 转换SysUserSysDepart对象转换SysUser
        List<UserDemandUnit> userDemandUnitList = JSON.parseArray(JSON.toJSONString(sysUserList), UserDemandUnit.class);

        for (UserDemandUnit userDemandUnit : userDemandUnitList) {
            QueryWrapper<SysUserDemand> sysUserDemandQueryWrapper = new QueryWrapper<>();
            sysUserDemandQueryWrapper.eq("user_id", userDemandUnit.getUserId());
            SysUserDemand sysUserDemand = userDemandService.getOne(sysUserDemandQueryWrapper);
            if (ObjectUtil.isNotNull(sysUserDemand)) {
                DemandUnit demandUnit = demandUnitService.getById(sysUserDemand.getDemandUnitId());
                if (ObjectUtil.isNotNull(demandUnit)) {
                    userDemandUnit.setDemandUnitName(demandUnit.getDemandUnitName());
                    userDemandUnit.setDemandUnitCreateTime(demandUnit.getCreateTime());
                }
            }
        }

        return Result.success(new PageData(getUserDemandResultMap(userDemandUnitList), new PageInfo(pageSize, currentPage, (int) sysUserPage.getTotal())));
    }

    @Override
    public Result<Object> updateUserAndQuote(String userId, Integer type, List<String> quoteIds) {
        if (type == 1) {
            // 新增
            quoteIds.stream()
                    .filter(quoteId -> ObjectUtil.isNotNull(answerQuoteService.getById(quoteId)))
                    .forEach(quoteId -> userQuoteService.save(new UserQuote(quoteId, userId)));
            return Result.success();
        } else if (type == 2) {
            // 删除
            QueryWrapper<UserQuote> userQuoteQueryWrapper = new QueryWrapper<>();
            userQuoteQueryWrapper.eq("user_id", userId).in("quote_id", quoteIds);

            userQuoteService.remove(userQuoteQueryWrapper);
            return Result.success();
        }
        return Result.fail();
    }

    /**
     * 查找登录用户管理用户id
     *
     * @return 被管理用户id集合
     */
    private List<String> getManageUserIds() {
        SysUser loginUser = sysUserService.getUserInfo2().getSysUser();
        List<String> manageUserIds = sysUserMapper.selectUserIds(loginUser.getUserId());
        return manageUserIds;
    }

    /**
     * 把实体字段换成动态表格标准
     *
     * @param userList 用户列表
     * @return 动态表格标准用户列表
     */
    private List<Map<String, Object>> getUserResultMap(List<SysUser> userList) {
        // 把实体字段换成动态表格标准
        List<Map<String, Object>> result = new ArrayList<>();
        for (SysUser sysUser : userList) {
            Map<String, Object> map = new HashMap<>();
            Field[] fields = sysUser.getClass().getDeclaredFields();
            for (Field field : fields) {
                try {
                    // 这个是，有的字段是用private修饰的 将他设置为可读
                    field.setAccessible(true);
                    String fieldsName = "sys_user_" + FieldsUtils.humpToUnderline(field.getName());
                    if ("sys_user_role_name".equals(fieldsName)) {
                        fieldsName = "sys_role_role_name";
                    }
                    Object fieldsValue = field.get(sysUser);
                    map.put(fieldsName, fieldsValue);
                } catch (Exception e) {
                    throw new CustomException(e);
                }
            }
            result.add(map);
        }
        return result;
    }

    /**
     * 把实体字段换成动态表格标准
     *
     * @param projectList 项目列表
     * @return 动态表格标准项目列表
     */
    private List<Map<String, Object>> getProjectResultMap(List<Project> projectList) {
        // 把实体字段换成动态表格标准
        List<Map<String, Object>> result = new ArrayList<>();
        for (Project project : projectList) {
            Map<String, Object> map = new HashMap<>();
            Field[] fields = project.getClass().getDeclaredFields();
            for (Field field : fields) {
                try {
                    // 这个是，有的字段是用private修饰的 将他设置为可读
                    field.setAccessible(true);
                    String fieldsName = "p_project_" + FieldsUtils.humpToUnderline(field.getName());
                    Object fieldsValue = field.get(project);
                    map.put(fieldsName, fieldsValue);
                } catch (Exception e) {
                    throw new CustomException(e);
                }
            }
            result.add(map);
        }
        return result;
    }

    /**
     * 把实体字段换成动态表格标准
     *
     * @param userDemandUnitList 项目列表
     * @return 动态表格标准项目列表
     */
    private List<Map<String, Object>> getUserDemandResultMap(List<UserDemandUnit> userDemandUnitList) {
        // 把实体字段换成动态表格标准
        List<Map<String, Object>> result = new ArrayList<>();
        for (UserDemandUnit userDemandUnit : userDemandUnitList) {
            Map<String, Object> map = new HashMap<>();
            Field[] fields = userDemandUnit.getClass().getDeclaredFields();
            for (Field field : fields) {
                try {
                    // 这个是，有的字段是用private修饰的 将他设置为可读
                    field.setAccessible(true);
                    String fieldsName = "sys_user_" + FieldsUtils.humpToUnderline(field.getName());
                    if ("sys_user_demand_unit_name".equals(fieldsName)) {
                        fieldsName = "p_demand_unit_demand_unit_name";
                    }
                    if ("sys_user_demand_unit_create_time".equals(fieldsName)) {
                        fieldsName = "p_demand_unit_create_time";
                    }
                    Object fieldsValue = field.get(userDemandUnit);
                    map.put(fieldsName, fieldsValue);
                } catch (Exception e) {
                    throw new CustomException(e);
                }
            }
            result.add(map);
        }
        return result;
    }

    /**
     * 通过拥有角色判断登录账号是否为管理员
     *
     * @param roleList 账号拥有角色
     * @return true 是，false 否
     */
    public Boolean isAdmin(List<SysRole> roleList) {
        List<String> roleKey = new ArrayList<>();
        roleKey.add(UserConstant.TOP_ROLE1);
        roleKey.add(UserConstant.TOP_AGENCIES);

        return roleList.stream().allMatch(role -> roleKey.contains(role.getRoleKey()));
    }

    /**
     * 获取所有管理员账号信息
     *
     * @return 所有管理员账号信息
     */
    private List<SysUser> getAdmin() {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_key", UserConstant.TOP_ROLE1).or().eq("role_key", UserConstant.TOP_AGENCIES);
        return getUsers(queryWrapper);
    }

    /**
     * 获取所有子代理机构账号信息
     *
     * @return 所有子代理机构账号信息
     */
    private List<SysUser> getAgency() {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_key", UserConstant.CHILD_AGENCIES);
        return getUsers(queryWrapper);
    }

    /**
     * 封装用户返回信息
     *
     * @param userList 用户集合
     * @return 动态表格标准用户集合
     */
    private List<Map<String, Object>> composeUserInfo(List<SysUser> userList) {
        // 封装角色名
        for (SysUser sysUser : userList) {
            // 查找角色名称
            QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
            sysUserRoleQueryWrapper.eq("user_id", sysUser.getUserId());
            SysUserRole sysUserRole = sysUserRoleService.getOne(sysUserRoleQueryWrapper);
            sysUser.setRoleName(sysRoleService.getById(sysUserRole.getRoleId()).getRoleName());
        }

        // 把实体字段换成动态表格标准
        return getUserResultMap(userList);
    }

    private List<SysUser> getUsers(QueryWrapper<SysRole> queryWrapper) {
        List<SysRole> sysRoleList = sysRoleService.list(queryWrapper);
        List<SysUser> sysUserList = new ArrayList<>();
        for (SysRole sysRole : sysRoleList) {
            List<SysUserRole> sysUserRoleList = sysUserRoleService.list(new QueryWrapper<SysUserRole>().eq("role_id", sysRole.getRoleId()));
            sysUserRoleList.forEach(sysUserRole -> sysUserList.add(sysUserService.getById(sysUserRole.getUserId())));
        }
        return sysUserList;
    }

}